package com.wantup.demo03xd.part05.communication.demo2;

/**
 * @author Zhaoluowei
 * @version 1.0
 * @date 2019/7/3 15:27
 */
public class Medium {

    private int num = 0;
    //是库存
    private static final int TOTAL = 20;





    public synchronized void put() {
        if (num < TOTAL) {
            //继续生产
            System.out.println("新增库存 ---- 当前库存 " + ++num);

            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            notifyAll();
        } else {
            //库存满了 通知生产者进行等待
            try {
                System.out.println("新增库存 ---- 库存已满 " + num);
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }


    }

    public synchronized void take() {
        if (num > 0) {
            //消费
            System.out.println("消费库存 ---- 当前库存 " + --num);

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            notifyAll();
        } else {
            //等待
            try {
                System.out.println("消费库存 ---- 当前库存不足 " + num);
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


}
